package com.htj.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.htj.exception.SysException;
import com.htj.exception.TokenException;

import java.util.Calendar;
import java.util.Map;

public class JWTUtil {
    private static String SING = "!@#$%^&&*";

    /**
     * 获得Token
     * @param map
     * @return Token
     */
    public static String getToken(Map<String,String> map){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,7);
        //创建JWTbuilder
        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        String token = builder.withExpiresAt(instance.getTime()).//指定令牌过期时间
                sign(Algorithm.HMAC256(SING));//sign签名
        return token;
    }

    /**
     * 验证签名并且返回DecodedJWT
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token){
//        JWTUtil.verify("token").getClaim("").asInt();
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

}
